<template>
  <div class="order-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.onum" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.os" placeholder="请选择订单状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待付款" value="1" />
            <el-option label="已付款" value="2" />
            <el-option label="已发货" value="3" />
            <el-option label="已完成" value="4" />
            <el-option label="已取消" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.ordertime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list-card">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-button type="success" @click="handleBatchProcess">
              <el-icon><Operation /></el-icon>
              批量处理
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="orderList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="onum" label="订单编号" width="180" />
        <el-table-column prop="userId" label="收货人" width="100" />
        <el-table-column prop="receiveId" label="联系电话" width="120" />
        <el-table-column prop="ototal" label="订单金额" width="100">
          <template #default="scope">
            <span style="color: #e74c3c; font-weight: bold;">¥{{ scope.row.ototal }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="os" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.os)">
              {{ getStatusText(scope.row.os) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ordertime" label="下单时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleViewDetail(scope.row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button 
              v-if="scope.row.os === 2" 
              size="small" 
              type="success" 
              link 
              @click="handleShip(scope.row)">
              <el-icon><Promotion /></el-icon>
              发货
            </el-button>
            <el-button 
              v-if="scope.row.os === 3" 
              size="small" 
              type="warning" 
              link 
              @click="handleReturn(scope.row)">
              <el-icon><RefreshLeft /></el-icon>
              退货
            </el-button>
            <el-button 
              v-if="canCancel(scope.row.os)" 
              size="small" 
              type="danger" 
              link 
              @click="handleCancel(scope.row)">
              <el-icon><CircleClose /></el-icon>
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
      :close-on-click-modal="false">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.onum }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.os)">
              {{ getStatusText(currentOrder.os) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.ototal }}</el-descriptions-item>
          <el-descriptions-item label="积分">{{ currentOrder.ointegral }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ currentOrder.ordertime }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentOrder.onote }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>商品信息</h4>
          <el-table :data="[currentOrder]" style="width: 100%">
            <el-table-column prop="oexpinfo" label="商品名称" />
            <el-table-column prop="ototal" label="单价">
              <template #default="scope">¥{{ scope.row.ototal }}</template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="detail-section">
          <h4>收货信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收货人">{{ currentOrder.userId || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentOrder.receiveId || '暂无信息' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="400px">
      <el-form :model="shipForm" label-width="80px">
        <el-form-item label="物流公司">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="圆通快递" value="YTO" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="申通快递" value="STO" />
            <el-option label="韵达快递" value="YUNDA" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleShipSubmit">确定发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Promotion, RefreshLeft, CircleClose, Operation } from '@element-plus/icons-vue'
import { findAllOrder, updateOrderStatus } from '@/api/order'
onMounted(() => {
  getOrderList();
})
// 搜索表单
const searchForm = ref({
  onum: '',
  os: '',
  ordertime: null
})

// 订单列表
const orderList = ref([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 选中的订单
const selectedOrders = ref([])

// 当前订单详情
const currentOrder = ref(null)
const detailDialogVisible = ref(false)

// 发货对话框
const shipDialogVisible = ref(false)
const currentShipOrder = ref(null)

// 发货表单
const shipForm = reactive({
  company: '',
  trackingNo: ''
})


// 获取订单列表
const getOrderList = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await findAllOrder(params)
    
    if (res.status === 200) {
      // 直接使用后端返回的数据
      orderList.value = res.data
      total.value = res.data.length
    } else {
      ElMessage.error(res.message || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getOrderList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    onum: '',
    os: '',
    ordertime: null
  }
  currentPage.value = 1
  getOrderList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 批量处理
const handleBatchProcess = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择要处理的订单')
    return
  }
  ElMessage.success(`已选择 ${selectedOrders.value.length} 个订单进行批量处理`)
}

// 查看详情
const handleViewDetail = (row) => {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 发货
const handleShip = (row) => {
  currentShipOrder.value = row
  shipDialogVisible.value = true
}

// 确认发货（在发货对话框中点击确定）
const confirmShip = async () => {
  try {
    await ElMessageBox.confirm(`确认发货订单 ${currentShipOrder.value.onum} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateOrderStatus({
      oid: currentShipOrder.value.oid,
      os: 3 // 已发货状态
    })
    
    if (res.s === 200) {
      ElMessage.success('发货成功')
      getOrderList()
    } else {
      ElMessage.error(res.message || '发货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发货失败')
    }
  }
}

// 退货
const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm(`确认退货订单 ${row.onum} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateOrderStatus({
      oid: row.oid,
      os: 5 // 已取消状态
    })
    
    if (res.s === 200) {
      ElMessage.success('退货成功')
      getOrderList()
    } else {
      ElMessage.error(res.message || '退货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退货失败')
    }
  }
}

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(`确认取消订单 ${row.onum} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateOrderStatus({
      oid: row.oid,
      os: 5 // 已取消状态
    })
    
    if (res.s === 200) {
      ElMessage.success('取消成功')
      getOrderList()
    } else {
      ElMessage.error(res.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',    // 待付款
    2: 'success',    // 已付款
    3: 'primary',    // 已发货
    4: 'info',       // 已完成
    5: 'danger'      // 已取消
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待付款',
    2: '已付款',
    3: '已发货',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 判断是否可取消
const canCancel = (status) => {
  return status === 1 || status === 2 // 待付款或已付款状态可取消
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'bank': '银行卡'
  }
  return methodMap[method] || '未支付'
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrderList()
}

// 发货提交
const handleShipSubmit = async () => {
  try {
    const res = await updateOrderStatus({
      oid: currentShipOrder.value.oid,
      os: 3, // 已发货状态
      oexpinfo: shipForm.company + '-' + shipForm.trackingNo
    })
    
    if (res.s === 200) {
      shipDialogVisible.value = false
      ElMessage.success('发货成功')
      getOrderList()
      shipForm.company = ''
      shipForm.trackingNo = ''
    } else {
      ElMessage.error(res.message || '发货失败')
    }
  } catch (error) {
    ElMessage.error('发货失败')
  }
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.order-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.order-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #303133;
}

.mt-20 {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style>